package com.hornsun.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

/**
 * Created by 编译中... on 2018/6/23.
 */
public class DESUtil {


    private static final byte[] KEY ={(byte)0xa2,(byte)0x34,(byte)0xdf,(byte)0x5b,(byte)0xd2,(byte)0x31,(byte)0x78,(byte)0x02,(byte)0x8f,(byte)0x14,(byte)0x24,(byte)0xc4,(byte)0x1c,(byte)0xac,(byte)0x32,(byte)0x54,(byte)0x90,(byte)0x05,(byte)0x1f,(byte)0x2e,(byte)0x2c,(byte)0xe1,(byte)0x8e,(byte)0x09};
    private static final byte[] VECTOR = {(byte)0x5a,(byte)0x31,(byte)0x24,(byte)0x06,(byte)0x7a,(byte)0x15,(byte)0xfc,(byte)0xbf};

    /**
     * 密钥算法
     */
    private static final String KEY_ALGORITHM = "DESede";

    /**
     * 加密/解密算法 / 工作模式 / 填充方式
     * Java 6支持PKCS5Padding填充方式
     * Bouncy Castle支持PKCS7Padding填充方式
     */
    private static final String CIPHER_ALGORITHM = "DESede/CBC/PKCS5Padding";

    /**
     * des加密
     * @param source    源字符串
     * @return  加密后的密文
     * @throws Exception
     */
    public static String encrypt(String source) throws Exception {
        byte[] sourceBytes = source.getBytes("UTF-8");
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(VECTOR);
        cipher.init(Cipher.ENCRYPT_MODE,new SecretKeySpec(KEY, KEY_ALGORITHM),iv);
        byte[] decrypted = cipher.doFinal(sourceBytes);
        return Base64.encodeBase64String(decrypted);
    }

    public static String decrypt(byte[] encryptStr, byte[] key,byte[] vector) throws Exception {

        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(vector);
        cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(key, KEY_ALGORITHM),iv);
        byte[] decoded = cipher.doFinal(encryptStr);
        return new String(decoded, "UTF-8");
    }


}
